#!/bin/sh
##### This is my (demuredemeanor) personal pastebin upload script.
# Based on https://causal.agency/bin/up.html
#
# Content can be piped in, a file can be specified, and a few flags can be used.


## TODO: Terminal output option https://github.com/buildkite/terminal-to-html
## TODO: tmux to html? (tmux2html?)
## TODO: Consider adding png compression?

set -eu

readonly BaseURL='http://up.demu.red/pb/'
readonly WebDir='/var/www/up/pb/'
readonly sshHost='demu.red'
readonly Port='500'

upload() {
    local src ext ft ts rand Path
    src=$1
    ext=${src##*.}
    ## Change plain files to txt for better browser viewing
    ft=$(file -b --mime-type ${src})
    if [ "${ft}" = "text/plain" ]; then
        ext="txt"
    fi
    ts=$(date "+%Y-%m-%d")
    rand=$(openssl rand -hex 4)
    Path=$(printf '%s_%s.%s' "${ts}" "${rand}" "${ext}")
    scp -q -P ${Port} "${src}" "${sshHost}:${WebDir}${Path}"
    ssh -p ${Port} ${sshHost} chmod a+r "${WebDir}${Path}"
    echo "${BaseURL}${Path}"
}

temp() {
    temp=$(mktemp -d)
    trap "rm -r '${temp}'" EXIT
}

uploadText() {
    temp
    cat > "${temp}/input.txt"
    upload "${temp}/input.txt"
}

uploadCommand() {
    temp
    echo "$ $*" > "${temp}/exec.txt"
    "$@" >> "${temp}/exec.txt" 2>&1 || true
    upload "${temp}/exec.txt"
}

uploadHighlight() {
    temp
    highlight -i "$@" -o "${temp}/hi.html" -lIas nightshimmer
    upload "${temp}/hi.html"
}

uploadScreen() {
    temp
    scrot -m "${temp}/capture.png"
    upload "${temp}/capture.png"
}

#uploadTerminal() {
    #temp
    #cat > "${temp}/term.html" <<-EOF
    #<!DOCTYPE html>
    #<title>${1}</title>
    #<style>
    #$(scheme -s)
    #</style>
    #EOF
    #ptee "$@" | shotty -Bs >> "${temp}/term.html"
    #upload "${temp}/term.html"
#}

uploadTermSVG() {
    echo "run svg" ## DEBUG
    temp
    termtosvg -D 5000 ${temp}/term.svg
    upload ${temp}/term.svg
}

## Make sure to add new options to the getopts...
while getopts 'chstv' opt; do
    case "${opt}" in
        (c) fn=uploadCommand;;
        (h) fn=uploadHighlight;;
        (s) fn=uploadScreen;;
        (v) fn=uploadTermSVG;;
        #(t) fn=uploadTerminal;;
        (?) exit 1;;
    esac
done
shift $((OPTIND - 1))
[ $# -eq 0 ] && : ${fn:=uploadText}
: ${fn:=upload}

url=$($fn "$@")
printf '%s' "${url}" | xclip -selection c 2> /dev/null || true
echo "  ${url}"
